const checkPermission = ({ code, name }) => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: (res) => {
        console.log('getSetting >> ', res)
        const authStatus = res.authSetting[code];
        if (authStatus) {
          resolve();
        } else {
          reject();
        }
      },
      fail() {
        console.warn('获取设置失败');
      },
    });
    reject();
  });
};

const getPermission = ({ code, name }) => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: (res) => {
        const authStatus = res.authSetting[code];
        if (authStatus) {
          resolve();
        } else {
          // 用户未授权，请求授权
          const hasPermission = requestPermission(code, name);
          if (hasPermission) {
            resolve();
          } else {
            reject();
          }
        }
      },
      fail() {
        reject();
      },
    });
  });
};

const requestPermission = (code, name) => {
  console.log('requestPermission', code, name)
  // 请求用户授权
  wx.authorize({
    scope: code,
    success: () => {
      return true;
    },
    fail: (err) => {
      console.warn('请求用户授权失败', err)
      // 授权失败，提示用户手动开启权限
      wx.showModal({
        title: `获取${name}失败`,
        content: `获取${name}失败，请在【右上角】-小程序【设置】项中，将【${name}】开启。`,
        showCancel: false,
        confirmText: '去设置',
        confirmColor: '#FA550F',
        success: (res) => {
          if (res.confirm) {
            // 打开设置页面
            wx.openSetting({
              success: (settingData) => {
                if (settingData.authSetting[code]) {
                  return true;
                } else {
                  console.warn('用户未打开权限', name, code);
                  return false;// 用户仍然拒绝授权
                }
              }
            });
          }
        }
      });
    }
  });
  return false;
}

module.exports = {
  getPermission, checkPermission,
};
